﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YasharEl.Infrastructure.Core.Prototype;
using YasharEl.Infrastructure.Core.ServiceModel.Prototype;
using YasharEl.Infrastructure.ObjectFactory;
using YasharEl.Infrastructure.ObjectFactory.Adapters;

namespace YasharEl.Infrastructure.Core.ServiceModel.Adapters.Maps
{
    public class PropertyInstanceToPropertyAssignmentDTOMap : TypeMapConfigurationBase<IPropertyInstance, PropertyAssignmentDTO>
    {
        private readonly IDependencyResolver resolver;

        public PropertyInstanceToPropertyAssignmentDTOMap(IDependencyResolver resolver)
        {
            Contract.Requires<ArgumentNullException>(resolver != null, "resolver could not be null.");

            this.resolver = resolver;
        }

        protected override void BeforeMap(ref IPropertyInstance source)
        {
        }

        protected override void AfterMap(ref PropertyAssignmentDTO target, params object[] moreSources)
        {
            //Don't need
        }

        protected override PropertyAssignmentDTO Map(IPropertyInstance source)
        {
            PropertyAssignmentDTO target = new PropertyAssignmentDTO();

            ITypeAdapter typeAdapter = resolver.Resolve<ITypeAdapter>();

            target.PropertyDefinition = 
                typeAdapter.Adapt<IPropertyMapping, PropertyDefinitionDTO>(source.PropertyMapping);

            if (source.ValueReference != null)
            {
                target.ValueContainer = PropertyValueDTOFactory.CreateValueContainerDTO(source.PropertyMapping.PropertyDefinition.DataType.Value);
                if (target.ValueContainer != null)
                {
                    target.ValueContainer.Value = source.ValueReference.RealValue;
                }
            }

            return target;
        }
    }
}
